import { useState, useEffect, createContext, useContext } from 'react';
import { message } from 'antd';
import { api } from '../utils/api';

interface User {
  id: number;
  username: string;
  email: string;
  role: string;
  created_at: string;
}

interface AuthContextType {
  user: User | null;
  loading: boolean;
  login: (username: string, password: string) => Promise<boolean>;
  logout: () => void;
  checkAuth: () => Promise<boolean>;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export const useAuth = () => {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};

export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);

  const checkAuth = async (): Promise<boolean> => {
    try {
      const token = localStorage.getItem('admin_token');
      
      if (!token) {
        setLoading(false);
        return false;
      }
      console.log('/auth/profile');
      console.log('checkAuth token:',token);
      const response = await api.get('/auth/profile');

      
      if (response.data.success) {
        setUser(response.data.data);
        setLoading(false);
        return true;
      } else {
        localStorage.removeItem('admin_token');
        setUser(null);
        setLoading(false);
        return false;
      }
    } catch (error) {
      localStorage.removeItem('admin_token');
      setUser(null);
      setLoading(false);
      return false;
    }
  };

  const login = async (username: string, password: string): Promise<boolean> => {
    try {
      const response = await api.post('/auth/admin/login', {
        username,
        password
      });

      if (response.data.success) {
        const { token, user: userData } = {token:response.data.data.access_token,user:response.data.data.admin};
        localStorage.setItem('admin_token', token);
        setUser(userData);
        message.success('登录成功');
        return true;
      } else {
        message.error(response.data.message || '登录失败');
        return false;
      }
    } catch (error: any) {
      message.error(error.response?.data?.message || '登录失败');
      return false;
    }
  };

  const logout = () => {
    localStorage.removeItem('admin_token');
    setUser(null);
    message.success('已退出登录');
  };

  useEffect(() => {
    checkAuth();
  }, []);

  const value: AuthContextType = {
    user,
    loading,
    login,
    logout,
    checkAuth
  };

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  );
}; 